package server.handler.userHandler;

import com.alibaba.fastjson.JSONObject;
import common.EnvelopeMessage;
import common.bodies.RegisterBody;
import server.dao.UserDao;
import server.handler.SimpleHandler;
import server.session.Session;


public class RegisterHandler implements SimpleHandler {
    @Override
    public void handle(EnvelopeMessage msg, Session session) {
        RegisterBody body = JSONObject.toJavaObject((JSONObject) msg.getBody(), RegisterBody.class);
        System.out.println(body.getUsername() + "尝试注册");
        boolean flag = new UserDao().addUser(body);

        if (flag) {
            System.out.println("注册成功");
            JSONObject object = new JSONObject();
            object.put("success", "true");
            object.put("message", "注册成功");
            EnvelopeMessage back = new EnvelopeMessage("user", "register_result", object);
            session.send(JSONObject.toJSONString(back));
        } else {
            System.out.println("注册失败");
            JSONObject object = new JSONObject();
            object.put("success", "true");
            object.put("message", "注册成功");
            EnvelopeMessage back = new EnvelopeMessage("user","register_result",object);
            String json = JSONObject.toJSONString(back);
            System.out.println("服务端返回"+json);
            session.send(json);
        }
    }
}
